import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 用于向电话呼叫
 */
public class PhoneCallGenerator extends Thread {

    private CellularPhone phone;

    public PhoneCallGenerator(String name, CellularPhone thePhone) {
        super(name);
        phone = thePhone;
    }

    public void run() {

        // 生成20个电话
        for (int i = 0; i < 20; i++) {
            try {
                if (phone.getLock().tryLock()) {
                    phone.startCall(getName(), i + "");
                    Thread.sleep(new Random().nextInt(1000));
                    phone.endCall(getName(), i + "");
                    phone.getLock().unlock();
                    Thread.yield();
                } else {
                    phone.display("<" + getName() + ">: Busy, Call (" + i + ") dropped");
                }
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
